package cn.lingyangwl.agile.auth.controller;

import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.lingyangwl.agile.auth.model.*;
import cn.lingyangwl.agile.auth.model.rqrs.log.*;
import cn.lingyangwl.agile.auth.service.*;
import cn.lingyangwl.agile.common.security.annotation.*;
import cn.lingyangwl.agile.file.excel.*;
import cn.lingyangwl.agile.ram.*;
import cn.lingyangwl.framework.core.response.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 系统访问记录
 * 
 * @author shenguangyang
 */
@RestController
@RequestMapping("/loginLog")
public class LoginLogController {
    @Resource
    private AuthLoginLogService loginLogService;

    @GetMapping("/page")
    @RamResource(action = "auth:loginLog:query", name = "查询登录日志", type = ActionType.READ)
    public Resp<IPage<AuthLoginLog>> page(LoginLogPageReq req) {
        IPage<AuthLoginLog> page = loginLogService.pageLoginLog(req);
        return Resp.ok(page);
    }

    @RamResource(action = "auth:loginLog:export", name = "导出登录日志", type = ActionType.READ)
    @PostMapping("/export")
    public void export(HttpServletResponse response, LoginLogPageReq req) throws Exception {
        List<AuthLoginLog> list = loginLogService.list(req);
        ExportParams params = new ExportParams();
        params.setType(ExcelType.HSSF);
        CusExcelExportUtil.exportExcel(response, params, "登录日志.xls", AuthLoginLog.class, list);
    }


    @RamResource(action = "auth:loginLog:delete", name = "删除登录日志", type = ActionType.WRITE)
    @DeleteMapping("/deleteBatch")
    public Resp<?> deleteBatch(@RequestParam(value = "ids") Long[] loginLogIds) {
        return loginLogService.deleteBatch(loginLogIds) ? Resp.ok() : Resp.fail("删除失败");
    }


    @RamResource(action = "auth:loginLog:delete", name = "删除登录日志", type = ActionType.WRITE)
    @DeleteMapping("/delete")
    public Resp<?> delete(@RequestParam(value = "id") Long loginLogId) {
        return loginLogService.deleteBatch(new Long[] { loginLogId }) ? Resp.ok() : Resp.fail("删除失败");
    }

    @RamResource(action = "auth:loginLog:clean", name = "清除登录日志", type = ActionType.WRITE)
    @DeleteMapping("/clean")
    public Resp<?> clean() {
        loginLogService.clear();
        return Resp.ok();
    }

    /**
     * 删除多少天之前的日志
     * delete of task
     */
    @InnerAuth
    @PostMapping("/deleteLogTask")
    public Resp<Integer> deleteLogTask(@RequestParam("endTime") String endTime) {
        return Resp.ok(loginLogService.deleteLogTask(endTime));
    }
}